import os
import pandas as pd

daily_dict = {}

def get_daily_df(stock_name):
    if stock_name in daily_dict:
        return daily_dict[stock_name]
    
    if daily_share_file_exists(stock_name):
        df = pd.read_excel(get_daily_share_file_name(stock_name), index_col=0)

        df['stock'] = stock_name
        df['date'] = df.index.strftime('%Y-%m-%d')
        df['next_pct'] = df['pct'].shift(-1)

        df['open_pct'] = round( 100 * (df['open'] / df['close'].shift() - 1 ), 2)
        df['low_pct'] = round( 100 * (df['low'] / df['close'].shift() - 1 ), 2)
        df['high_pct'] = round( 100 * (df['high'] / df['close'].shift() - 1 ), 2)
        df['next_high_pct'] = df['high_pct'].shift(-1)

        # 计算均线
        df["5d"] = df["close"].rolling(window=5).mean()
        df["10d"] = df["close"].rolling(window=10).mean()
        df["15d"] = df["close"].rolling(window=15).mean()
        df["20d"] = df["close"].rolling(window=20).mean()
        df["30d"] = df["close"].rolling(window=30).mean()
        df["60d"] = df["close"].rolling(window=60).mean()
        df["75d"] = df["close"].rolling(window=75).mean()
        df["100d"] = df["close"].rolling(window=100).mean()  # 20W
        df["300d"] = df["close"].rolling(window=300).mean()  # 60W
        df["1200d"] = df["close"].rolling(window=1200).mean() 

        df["gt5d"] = round((100 * (df["close"] / df["5d"] - 1)), 2)
        df["gt10d"] = round((100 * (df["close"] / df["10d"] - 1)), 2)
        df["gt15d"] = round((100 * (df["close"] / df["15d"] - 1)), 2)
        df["gt20d"] = round((100 * (df["close"] / df["20d"] - 1)), 2)
        df["gt30d"] = round((100 * (df["close"] / df["30d"] - 1)), 2)
        df["gt60d"] = round((100 * (df["close"] / df["60d"] - 1)), 2)
        df["gt75d"] = round((100 * (df["close"] / df["75d"] - 1)), 2)
        df["gt100d"] = round((100 * (df["close"] / df["100d"] - 1)), 2)
        df["gt300d"] = round((100 * (df["close"] / df["300d"] - 1)), 2)
        df["gt1200d"] = round((100 * (df["close"] / df["1200d"] - 1)), 2)

        df['pct_3d'] = round((100 * (df["close"] / df["close"].shift(3) - 1)), 2)
        df['pct_5d'] = round((100 * (df["close"] / df["close"].shift(5) - 1)), 2)

        # 低点与均线的距离
        df["lowGt5d"] = round((100 * (df["low"] / df["5d"] - 1)), 2)
        df["lowGt10d"] = round((100 * (df["low"] / df["10d"] - 1)), 2)
        df["lowGt20d"] = round((100 * (df["low"] / df["20d"] - 1)), 2)
        df["lowGt30d"] = round((100 * (df["low"] / df["30d"] - 1)), 2) 

        # 计算累计最大值（峰值）
        cumulative_max = df["close"].cummax()
        df['drawdown'] = round( 100 * (df["close"] / cumulative_max - 1), 2)

        daily_dict[stock_name] = df
        return df
    
    return None

# 保存日数据的文件名
def get_daily_share_file_name(stock_name):
    return "data/share_daily/"+stock_name+".xlsx"

def daily_share_file_exists(stock_name):
    return os.path.exists(get_daily_share_file_name(stock_name))